<?php

namespace app\common\model;

use think\Model;
use think\Db;
use think\Session;

class Menu extends Model {

    protected function initialize() {
        parent::initialize();
    }

    /**
     * 构造层级菜单  
     * @param type $is_show 1为只取显示的菜单
     * @return type
     */
    public function getMenuTree($is_show='') {
        $where = '';
        if($is_show)
            $where .= ' and is_show = 1';
            
        // 取出所有顶级
        $data = Db::name($this->name)->where('parent_id=0'.$where)->select();
        if ($data) {
            // 循环每个顶级取二级
            foreach ($data as $k => $v) {
                $data[$k]['children'] = Db::name($this->name)->where('parent_id=' . $v['menu_id'].$where)->select();
                // 循环每个二级取三级
                if($data[$k]['children']){
                    foreach ($data[$k]['children'] as $k1 => $v1) {
                        $data[$k]['children'][$k1]['children'] = Db::name($this->name)->where('parent_id=' . $v1['menu_id'])->select();
                    }
                }
            }
            return $data;
        }
    }
    
    /**
     *获取权限节点
     * @param type $ids
     * @return type
     */
    public function getPermissions ($ids) {
        $permissions = Db::name($this->name)->where(['menu_id'=>['in',$ids]])->select();
        
        $node = [];
        $new_permissions = [];
        
        //找出parent_id == 0的菜单和可以访问的权限节点
        foreach ($permissions as $k=>$v){
            if($v['parent_id'] == 0){
                $new_permissions[] = $v;
            }
            if($v['module'] != 'null' && $v['controller'] != 'null' && $v['action'] != 'null'){
                $node[] = $v['module'].'/'.$v['controller'].'/'.$v['action'];
            }
        }
        
        //组装菜单层次树
        foreach ($new_permissions as $k=>$v){
            foreach ($permissions as $kk=>$vv){
                if($vv['parent_id'] == $v['menu_id']){
                    $new_permissions[$k]['children'][] = $vv;
                }
            }
        }
        
        //把可以访问的节点存在session中
        Session::set('node',$node);
        return $new_permissions;
    }
    
    
    
    /**
     * 查询菜单下子菜单的数量
     */
    public function getMenuSum ($menu_id) {
        return Db::name('Menu')->where('parent_id='.$menu_id)->count();
    }
    
    //获取菜单层级
    public function Tree() {
        return $this->_reSort(Db::name($this->name)->select());
    }

    // 递归对有的菜单进行重新排序
    private function _reSort($data, $parent_id = 0, $level = 0) {
        static $ret = array();
        foreach ($data as $k => $v) {
            if ($v['parent_id'] == $parent_id) {
                // 把level值放到这个分类里，这样就可以知道这个分类是第几级的
                $v['level'] = $level;
                $ret[] = $v;
                // 再找这个分类的子分类
                $this->_reSort($data, $v['menu_id'], $level + 1);
            }
        }
        return $ret;
    }
    

}
